/*----------------------------------------------------------------------*/
/* PROGRAM: der_MUO.ado							*/						
/*									*/
/* PURPOSE:								*/
/* [*] 	This code derives the MUO([x,]p) function given any functional 	*/
/*	form of the AUO([x,]p) function. It uses Mata, which is a 	*/
/*	special language in Stata for manipulating matrices. 		*/
/*	In our case, the most useful feature of Mata is being able to 	*/
/*	take derivatives of polynomials.				*/
/*									*/
/* USE ON:								*/
/* [*] 	This is a procedure that does not use the Stata data set as 	*/
/*	input, but rather uses a matrix	specified by the user. See the 	*/
/*	"Inputs" section below on how to specify the input matrix.	*/				
/*									*/
/* INPUTS:								*/
/* [*] 	arg_AUO_matrix:	The matrix containing the polynomial expression */
/*	for AUO([x,]p). This matrix should have one row and M+1 columns,*/
/*	where M is the order of the polynomial. The first term in the 	*/
/*	matrix is the intercept, the second the linear term, etc. The 	*/
/*	code will work (efficiently) on any (reasonable) polynomial 	*/
/*	order M.							*/
/*									*/
/* OUTPUTS:								*/
/* [*]	MUO_matrix: The matrix containing the polynomial expression for	*/
/*	MUO([x,] p). This matrix should	have one row and M+1 columns, 	*/
/*	where M is the order of the polynomial (as dictated by the order*/
/*	of AUO([x,]p) -- MUO([x,]p) must be the same order as AUO([x,]p)*/
/*	The first term in the is the intercept,the second the linear 	*/
/*	term etc.							*/
/*									*/
/* EXAMPLE CALL TO PROCEDURE:						*/
/* matrix test = J(1,2,.)						*/
/*									*/
/* matrix test[1,1] = 10582.29						*/
/* matrix test[1,2] = -11800.62						*/
/*									*/
/* der_MUO test								*/
/*----------------------------------------------------------------------*/

capture program drop der_MUO

program der_MUO
	args arg_AUO_matrix
	marksample touse
	
	* Execute in Mata
	mata: calc_MUO("`arg_AUO_matrix'")
		
end

* Define the function for deriving MUO([x,]p) in Mata
mata:
	void calc_MUO(string scalar sc_AUO_name)
	{
		cm = st_matrix(sc_AUO_name)
			
		/* Multiply AUO([x,]p) by (1-p)*/
			for_der_MUO = polymult(cm, (1, -1))
			
		/* Take the derivative of (1-p)*AUO([x,]p) with respect to p*/
			MUO_neg = polyderiv(for_der_MUO, 1)
			
		/* Multiply the derivative by -1 */
		/*[because we took the derivative with respect to p instead of (1-p)] */
			MUO_matrix = polymult(MUO_neg, (-1))
			
		/* Export to Stata as a matrix*/
			st_matrix("MUO_matrix", MUO_matrix)
			
	}
end
